package com.gusti.mensajes.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gusti.mensajes.dao.IMessageDao;
import com.gusti.mensajes.model.ConversationThread;
import com.gusti.mensajes.model.Message;
import com.gusti.mensajes.model.User;
import com.gusti.mensajes.util.Debug;

/**
 * 
 * @author gusti
 *
 */
@Repository
public class MessageDao extends ProjectDao<Message> implements IMessageDao {

	public ConversationThread searchConversationThread( User participantOne, User participantTwo ) {
		ConversationThread conversationThread = new ConversationThread();
		
		Query query = null;
		try {
			query = em.createQuery( "FROM ConversationThread as ct WHERE ct.participantOne = :participantOne AND ct.participantTwo = :participantTwo OR ct.participantOne = :participantTwo AND ct.participantTwo = :participantOne" );
			query.setParameter( "participantOne", participantOne );
			query.setParameter( "participantTwo", participantTwo );
			conversationThread = (ConversationThread)query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
		}
		
		return conversationThread;
	}
	
	@SuppressWarnings("unchecked")
	public List<ConversationThread> listConversation( User user ) {
		List<ConversationThread> conversationThreads = new ArrayList<ConversationThread>();
		
		Query query = null;
		try {
			query = em.createQuery( "FROM ConversationThread as ct WHERE ct.participantOne = :user OR ct.participantTwo = :user" );
			query.setParameter( "user", user );
			conversationThreads = (List<ConversationThread>)query.getResultList();
		} catch ( Exception e ) {
			Debug.error( e );
		}
		
		return conversationThreads;
	}

	@SuppressWarnings("unchecked")
	public List<Message> viewConversation( long conversationId ) {
		List<Message> messages = new ArrayList<Message>();
		
		Query query = null;
		try {
			query = em.createQuery( "FROM Message as msg WHERE msg.conversationThread.id = :conversationId" );
			query.setParameter( "conversationId", conversationId );
			messages = (List<Message>)query.getResultList();
		} catch ( Exception e ) {
			Debug.error( e );
		}
		
		return messages;
	}
	
}
